<?php

class Application_Model_AssocOffrAddrMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_AssocOffrAddr');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_AssocOffrAddr $assocoffraddr)
	{
		$data = array(
				'id_offer'   	=> $assocoffraddr->getOfferId(),
				'id_address'	=> $assocoffraddr->getAddressId(),
		);
		
		if ((null === ($id1 = $assocoffraddr->getOffrAddrId()))) {
			unset($data['id_offraddr']);
			return $this->getDbTable()->insert($data);
		} 
	}
	
	public function saveOfferAddresses(int $id_offer,array $addresses)
	{
		
		foreach($addresses as $address)
		{
			$data = array(
					'id_offer'   	=> $id_offer,
					'id_address'	=> $address->getAddressId(),
			);
			$this->getDbTable()->insert($data);
		}
		
	}
	
	/**
	 * Find the addresses list of the offer
	 *
	 * @param int $id_offer
	 * @return array of the Application_Model_Image
	 */
	public function findAddresses($id_offer)
	{
		$where = array('id_offer = ?' => $id_offer);
		$rows = new Zend_Db_Table_Row();
		$rows = $this->getDbTable()->fetchAll($where);
		if (0 == count($rows)) {
			return array();
		}
	
		$addresses = array();
		foreach ($rows as $row)
		{
			$addressMapper = new Application_Model_AddressMapper();
			$address = $addressMapper->find($row->id_address, new Application_Model_Address());
			$addresses[] = $address;
		}
		return $addresses;
	}
	
	public function delete($where){
		$result = $this->getDbTable()->fetchAll($where);
		if (0 != count($result)) {
			$this->getDbTable()->delete($where);
		}
	}
	
	
}